package com.codefish.framework.spring.aop.framework;

import com.codefish.framework.spring.aop.framework.cglib.MethodInterceptorAdapter;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;

/**
 * 使用cglib实现动态代理
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/10/17 下午 06:57
 */
public class CglibAopProxy implements IAopProxy {
    AdviseSupport adviseSupport;

    public CglibAopProxy(AdviseSupport adviseSupport) {
        this.adviseSupport = adviseSupport;
    }


    @Override
    public Object getProxy() {
        //创建Enhancer对象
        Enhancer enhancer = createEnhancer();
        //设置代理对象的父类对象为被代理对象的类对象
        enhancer.setSuperclass(adviseSupport.getTargetResource().targetClass());
        //从adviseSupport获取cglib的方法拦截器
        enhancer.setCallback(getCallback(adviseSupport));
        //无参构造创建代理对象实例
        return enhancer.create();
    }

    /**
     * 从adviseSupport获取cglib的方法拦截器
     */
    private Callback getCallback(AdviseSupport adviseSupport) {
        return new MethodInterceptorAdapter(adviseSupport.getMethodInterceptor(), adviseSupport.getMethodMatcher());
    }

    /**
     * 从adviseSupport获取cglib的方法拦截器
     */
    private Enhancer createEnhancer() {
        return new Enhancer();
    }

}
